package world.criver.imagecompresstool.function;

import net.coobird.thumbnailator.Thumbnails;
import com.monchstudio.image.png.PngCompressor;
import world.criver.imagecompresstool.data.daConfig;

import java.io.File;
import java.util.ArrayList;

public class funThumb {
    public static final String mode_auto="compress0";
    public static final String mode_1="compress1";
    public static final String mode_2="compress2";
    public static final String mode_3="compress3";
    /**
     * 压缩图片
     * @param of
     * @return list<[old_name,old_size,result,new_name,new_size]>
     */
    public ArrayList<String[]> thumb(File of, String mode) {
        ArrayList<String[]> re=new ArrayList<>();
        switch (mode){
            case mode_2 -> re.add(getThumbResult(of,0.9,"high"));
            case mode_1 -> re.add(getThumbResult(of,0.7,"medium"));
            case mode_3 -> re.add(getThumbResult(of,0.5,"low"));
            default -> {
                re.add(getThumbResult(of,0.9,"high"));
                re.add(getThumbResult(of,0.7,"medium"));
                re.add(getThumbResult(of,0.5,"low"));
            }
        }
        return re;
    }
    private String[] getThumbResult(File o,double q,String mode){
        String name="";
        long ol=o.length();
        if(daConfig.compress_replace)name=o.getName();
        else name=o.getName().replaceAll("\\.png","_thumb_"+mode+".png").replaceAll("\\.jpg","_thumb_"+mode+".jpg");
        File n=new File(o.getParent()+"/"+name);
        boolean r=false;
        if(o.getName().endsWith(".png"))r=thumbPng(o,n);
        else if(o.getName().endsWith(".jpg"))r=thumbJpg(o,n,q);
        return new String[]{o.getName(),ol+"",r+"",n.getName(),(r?n.length():0)+""};
    }
    private boolean thumbJpg(File of,File nf,double quality){
        try {
            Thumbnails.of(of)
                    .scale(1)
                    .outputQuality(quality)
                    .toFile(nf);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
    private boolean thumbPng(File of,File nf){
        try {
            PngCompressor.compress(of, nf);
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
